package com.hjm.strategy.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hjm.common.api.ls.leshua.LeShuaUtil;
import com.hjm.common.api.ls.leshua.entity.*;
import com.hjm.common.api.ls.leshua.ls.ImageUtil;
import com.hjm.common.utils.StringUtils;
import com.hjm.framework.config.BlueConfig;
import com.hjm.framework.config.CustomConfig;
import com.hjm.framework.web.domain.AjaxResult;
import com.hjm.project.channel.agent.domain.ChannelAgent;
import com.hjm.project.channel.agent.domain.request.AgentRequest;
import com.hjm.project.channel.agent.domain.request.MerchantPicDto;
import com.hjm.project.channel.payment.domain.ChannelPayment;
import com.hjm.strategy.AgentStrategy;
import com.hjm.strategy.Channel;
import com.hjm.strategy.kdb.UploadUtil;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Base64;
import java.util.Map;

@Channel("LS")
@Component
public class LeshuaAgentStrategy implements AgentStrategy {


    @Override
    public void addAgent(ChannelAgent channelAgent, AgentRequest agentRequest) {
        Map<String, Object> baseResult = LeShuaUtil.commonRemote(agentRequest, CustomConfig.getBaseUrl() + "/agentInfo/subAgent", CustomConfig.getSignKey());
        if (StringUtils.equals(baseResult.get("resultCode").toString(), "0000")) {
            channelAgent.setStatus("1");
            Map<String, Object> respData = (Map<String, Object>) baseResult.get("respData");
            channelAgent.setCAgentId(respData.get("agentId").toString());
        } else {
            channelAgent.setStatus("-1");
        }
        channelAgent.setChannelResponse(JSON.toJSONString(baseResult));
    }

    @Override
    public void updateAgent(ChannelAgent channelAgent, AgentRequest agentRequest) {
        Map<String, Object> baseResult = LeShuaUtil.commonRemote(agentRequest, CustomConfig.getBaseUrl() + "/agentInfo/subAgent", CustomConfig.getSignKey());
        channelAgent.setChannelResponse(JSON.toJSONString(baseResult));
        if (StringUtils.equals(baseResult.get("resultCode").toString(), "0000")) {
            channelAgent.setStatus("1");
        } else if (StringUtils.equals(baseResult.get("resultCode").toString(), "-5001")) {
            //{resultCode=-5001, resultMsg=代理商账号已经存在}
            channelAgent.setStatus("2");
        } else if (StringUtils.equals(baseResult.get("resultCode").toString(), "-8001")) {
            //{resultCode=-8001, resultMsg=代理商编号[100023057]不存在！修改失败！}
            channelAgent.setStatus("-1");
        }
    }

    @Override
    public String uploadFile(String localPath) {
        try {
            String ext = localPath.split("\\.")[1];
            String base64 = UploadUtil.resolveBase64(localPath);
            MerchantPicDto merchantPicDto = new MerchantPicDto();
            merchantPicDto.setAgentId(CustomConfig.getSubAgentId());
            merchantPicDto.setSource(CustomConfig.getSource());
            merchantPicDto.setExt(ext);//扩展名，例如jpg/png;pdf
            merchantPicDto.setPicData(base64);//base64编码的图片数据
            merchantPicDto.setSign(LeShuaUtil.md5ParamByKey(merchantPicDto, ""));//签名
            Map<String, Object> baseResult = LeShuaUtil.commonRemote(merchantPicDto, CustomConfig.getBaseUrl() + "/basicInfo/uploadMerchantPic", CustomConfig.getSignKey());
            Map<String, String> respData = (Map<String, String>) baseResult.get("respData");
            return respData.get("pictureTmpUrl");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void transfer(ChannelPayment channelPayment) {
        try {
            Transfer transfer = new Transfer();
            transfer.setSource(CustomConfig.getSource());
            transfer.setObjectSrcId(channelPayment.getAgentId());
            transfer.setObjectDstId(channelPayment.getDstAgentId());
            transfer.setTransferMode(channelPayment.getTransferMode());
            transfer.setAmount(LeShuaUtil.changeMoneyToFen(channelPayment.getApplyAmount()));
            transfer.setBusinessNo(channelPayment.getBusinessNo());
            Map<String, Object> baseResult = LeShuaUtil.commonRemote(transfer, CustomConfig.getBaseUrl() + "/behalfPay/transfer", CustomConfig.getSignKey());
            if (StringUtils.equals(baseResult.get("resultCode").toString(), "0000")) {
                JSONObject respData = (JSONObject) baseResult.get("respData");
                if (respData.getString("state").equals("1")) {
                    //转账中
                    channelPayment.setStatus(3);
                } else if (respData.getString("state").equals("2")) {
                    //转账成功
                    channelPayment.setStatus(1);
                } else if (respData.getString("state").equals("3")) {
                    //转账失败
                    channelPayment.setStatus(2);
                }
            } else {
                channelPayment.setStatus(2);
            }
            channelPayment.setRemark(baseResult.get("resultMsg") + "");

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void queryTransfer(ChannelPayment channelPayment) {
        TransferOrderInfo transferOrderInfo = new TransferOrderInfo();
        transferOrderInfo.setSource(CustomConfig.getSource());
        transferOrderInfo.setBusinessNo(channelPayment.getBusinessNo());
        Map<String, Object> baseResult = LeShuaUtil.commonRemote(transferOrderInfo, CustomConfig.getBaseUrl() + "/behalfPay/transferOrderInfo", CustomConfig.getSignKey());
        if (StringUtils.equals(baseResult.get("resultCode").toString(), "0000")) {
            JSONObject respData = (JSONObject) baseResult.get("respData");
            if (respData.getString("state").equals("1")) {
                //转账中
                channelPayment.setStatus(3);
            } else if (respData.getString("state").equals("2")) {
                //转账成功
                channelPayment.setStatus(1);
            } else if (respData.getString("state").equals("3")) {
                //转账失败
                channelPayment.setStatus(2);
            }
        } else {
            channelPayment.setStatus(2);
        }
        channelPayment.setRemark(baseResult.get("resultMsg") + "");
    }

    @Override
    public void withdraw(ChannelPayment channelPayment) {
        try {
            SubmitWithdraw submitWithdraw = new SubmitWithdraw();
            submitWithdraw.setAgentId(channelPayment.getAgentId());
            submitWithdraw.setSource(CustomConfig.getSource());
            submitWithdraw.setApplyAmount(LeShuaUtil.changeMoneyToFen(channelPayment.getApplyAmount()));
            submitWithdraw.setBankAccountType(channelPayment.getBankAccountType());
            submitWithdraw.setAccountType(channelPayment.getAccountType());
            submitWithdraw.setApplyAgentId(channelPayment.getApplyAgentId());
            submitWithdraw.setInvoiceType(channelPayment.getInvoiceType());
            submitWithdraw.setBusinessNo(channelPayment.getBusinessNo());
            Map<String, Object> baseResult = LeShuaUtil.commonRemote(submitWithdraw, CustomConfig.getBaseUrl() + "/merchantinfo/v3/submitWithdraw", CustomConfig.getSignKey());
            if (StringUtils.equals(baseResult.get("resultCode").toString(), "0000")) {
                channelPayment.setStatus(3);
            } else {
                channelPayment.setStatus(2);
            }
            channelPayment.setRemark(baseResult.get("resultMsg") + "");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public void queryWithdraw(ChannelPayment channelPayment) {
        QueryWithdraw queryWithdraw = new QueryWithdraw();
        queryWithdraw.setAgentId(channelPayment.getAgentId());
        queryWithdraw.setSource(CustomConfig.getSource());
        queryWithdraw.setWithdrawAgentNo(channelPayment.getApplyAgentId());
        queryWithdraw.setBusinessNo(channelPayment.getBusinessNo());
        Map<String, Object> baseResult = LeShuaUtil.commonRemote(queryWithdraw, CustomConfig.getBaseUrl() + "/merchantinfo/v3/queryWithdrawState", CustomConfig.getSignKey());
        if (StringUtils.equals(baseResult.get("resultCode").toString(), "0000")) {
            JSONObject respData = (JSONObject) baseResult.get("respData");
            if (StringUtils.equals(respData.getString("F_state"), "9")) {
                channelPayment.setStatus(1);
                channelPayment.setRemark("打款成功");
            } else if (StringUtils.equals(respData.getString("F_state"), "-1")) {
                channelPayment.setStatus(3);
                channelPayment.setRemark("待打款");
            } else {
                channelPayment.setStatus(2);
                channelPayment.setRemark("打款失败");
            }

        } else {
            channelPayment.setStatus(2);
            channelPayment.setRemark(baseResult.get("resultMsg") + "");
        }
    }

    @Override
    public AccountAmount queryBalance(ChannelAgent channelAgent) {
        TermDto termDto = new TermDto();
        termDto.setAgentId(channelAgent.getCAgentId());
        termDto.setSource(CustomConfig.getSource());
        AccountAmount amount = new AccountAmount();
        Map<String, Object> baseResult = LeShuaUtil.commonRemote(termDto, CustomConfig.getBaseUrl() + "/merchantinfo/v3/queryAccountAmount", CustomConfig.getSignKey());
        if (StringUtils.equals(baseResult.get("resultCode").toString(), "0000")) {
            JSONObject respData = (JSONObject) baseResult.get("respData");
            amount.setDepositAmount(LeShuaUtil.changeMoneyToYuan(respData.getString("depositAmount")));
            amount.setPartnerRebateDepositAmount(LeShuaUtil.changeMoneyToYuan(respData.getString("partnerRebateDepositAmount")));
            amount.setProfitAccount(LeShuaUtil.changeMoneyToYuan(respData.getString("profitAccount")));
            amount.setPartnerDepositAmount(LeShuaUtil.changeMoneyToYuan(respData.getString("partnerDepositAmount")));
            amount.setRebateDepositAmount(LeShuaUtil.changeMoneyToYuan(respData.getString("rebateDepositAmount")));
            amount.setInvoiceRemainAmount(LeShuaUtil.changeMoneyToYuan(respData.getString("invoiceRemainAmount")));
            return amount;
        }
        return null;
    }

    public static String convertImageToBase64(String imagePath) throws IOException {
        // 通过 Hutool 下载图片字节流
        byte[] imageBytes = HttpUtil.downloadBytes(imagePath);
        // Base64 编码
        return Base64.getEncoder().encodeToString(imageBytes);
    }
}